/**
 *区域查询
 */
'use strict';

const conn = require('../../libs/DB/Conn');
const _ = require('underscore');
const rangeCascadeQuery = require("../range/rangeTreeQueryAction");

module.exports = async function (params) {

    let domainList = await conn(`
                                 SELECT
                                     df.domain_id AS domainId,
                                     df.domain_name AS domainName,
                                     df.address,
                                     df.manager_name AS managerName,
                                     df.manager_mobile AS managerMobile,
                                     dc.lng,
                                     dc.lat
                                 FROM domain_file df
                                 LEFT JOIN domain_coordinate dc ON dc.domain_id = df.domain_id
                                 WHERE
                                    df.domain_id = ${params.userDomainId} AND 
                                    df.delete_sign = 1;
                                        `);
    let domainGroup = _.groupBy(domainList,"domainId");
    let dataList = [];
    for(const domainId in domainGroup){
        let domainPointList = domainGroup[domainId];
        let pointList = [];
        if(domainPointList[0].lng && domainPointList[0].lat){
            let centerLng = 0;
            let centerLat = 0;
            for(const domainPoint of domainPointList){
                pointList.push([domainPoint.lng,domainPoint.lat]);
                centerLng += domainPoint.lng;
                centerLat += domainPoint.lat;
            }
            centerLng = Math.floor(centerLng/pointList.length * 1000000)/1000000;
            centerLat = Math.floor(centerLat/pointList.length * 1000000)/1000000;
            domainPointList[0].centerPoint = [centerLng,centerLat]
        }
        delete domainPointList[0].lng;
        delete domainPointList[0].lat;
        domainPointList[0].pointList = pointList;

        dataList.push(domainPointList[0]);
    }
    let rangeInfo = await rangeCascadeQuery(params);
    return {success:true,domainInfo:dataList[0],rangeList:rangeInfo.dataList};
};
